<script lang="ts" setup>
import { ref, defineProps, withDefaults, defineEmits } from "vue"
import { Plus } from "@element-plus/icons-vue"
import { ElButton, ElDialog, ElMessage } from "element-plus"
import type { FormInstance, FormRules, UploadProps } from "element-plus"
import { type RuleForm } from "@/api/wallpaper/types/banner.ts"

const props = withDefaults(
  defineProps<{
    dialogVisible: boolean
  }>(),
  { dialogVisible: false }
)

const ruleFormRef = ref<FormInstance>()
const visible = ref(false)
watchEffect(() => {
  visible.value = props.dialogVisible
})
const ruleForm = ref<RuleForm>({
  name: "",
  sort: "",
  url: "",
  way: "",
  id: ""
})
const rules = reactive<FormRules<RuleForm>>({
  file: [{ required: true, message: "缩略图必填", trigger: "change" }],

  sort: [
    {
      required: true,
      message: "序号必填",
      trigger: "blur"
    }
  ],
  url: [
    {
      required: true,
      message: "跳转地址必填",
      trigger: "blur"
    }
  ],
  way: [
    {
      required: true,
      message: "跳转方式必填",
      trigger: "blur"
    }
  ]
})
const fileChange = (uploadFile, fileList) => {
  ruleForm.value.file = uploadFile

  if (fileList.length !== 0) {
    ruleFormRef.value.validateField("file")
  }
}

const fileRemove = (uploadFile, fileList) => {
  if (fileList.length === 0) {
    ruleForm.value.file = null
    ruleFormRef.value.validateField("file")
  }
}

const emits = defineEmits(["closeDialog"])
const handleClose = () => {
  emits("closeDialog")
}
const imageUrl = ref("")

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/png") {
    ElMessage.error("Avatar picture must be JPG format!")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!")
    return false
  }
  return true
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!")
    } else {
      console.log("error submit!", fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  handleClose()
}
</script>

<template>
  <el-dialog v-model="visible" title="新增壁纸" width="560" :before-close="handleClose">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="mrg-t-20">
      <el-form-item label="缩略图" prop="file">
        <el-upload
          class="avatar-uploader"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          accept=".png,.jpg,.jpeg"
          :on-change="fileChange"
          :on-remove="fileRemove"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="序号" prop="sort">
        <el-input v-model="ruleForm.sort" placeholder="请输入序号"
      /></el-form-item>
      <el-form-item label="跳转地址" prop="url">
        <el-input v-model="ruleForm.url" placeholder="请输入跳转地址" />
      </el-form-item>

      <el-form-item label="跳转方式" prop="way">
        <el-radio-group v-model="ruleForm.way">
          <el-radio value="standard">站内</el-radio>
          <el-radio value="high">站外</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row justify="end">
        <el-form-item>
          <el-button class="base-btn" @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
